const redis = require('../redis/init.js');

module.exports = async (req, res, next) => {
  const maxSize = 100;
  const { currentPage = 1, size = 10 } = req.query;

  const page = parseInt(currentPage, 10);
  const pageSize = Math.min(parseInt(size, 10), maxSize);

  if (isNaN(page) || isNaN(pageSize) || page < 1 || pageSize < 1) {
    return res.status(400).json({ error: "Invalid pagination parameters" });
  }

  const start = (page - 1) * pageSize;
  const end = start + pageSize - 1;

  try {
    const listLength = await redis.lLen("articlesList");

    if (start >= listLength) {
      return res.status(200).json({ articles: [], message: "Page out of range" });
    }

    const articles = await redis.lRange("articlesList", start, end);
    const parsedArticles = articles.map((article) => {
      try {
        return JSON.parse(article);
      } catch (error) {
        console.warn("Invalid article format:", article, error);
        return null;
      }
    });

    req.articles = parsedArticles.filter((article) => article !== null) || [];
    next();
  } catch (error) {
    console.error("Error fetching articles from Redis:", error);
    next(error);
  }
};
